package cn.sharp.bbs.service.impl;

import cn.sharp.bbs.common.Constants;
import cn.sharp.bbs.dao.gen.LetterMapper;
import cn.sharp.bbs.dao.gen.LettercontentMapper;
import cn.sharp.bbs.dao.gen.UserMapper;
import cn.sharp.bbs.dao.msg.ChatDao;
import cn.sharp.bbs.entity.BO.CurrentUser;
import cn.sharp.bbs.entity.DO.ChatRoom;
import cn.sharp.bbs.entity.DO.Letter;
import cn.sharp.bbs.entity.DO.Lettercontent;
import cn.sharp.bbs.entity.DO.User;
import cn.sharp.bbs.event.LetterEvent;
import cn.sharp.bbs.service.ChatService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ChatServiceImpl implements ChatService {

    @Resource
    private ChatDao chatDao;

    @Resource
    private LettercontentMapper lettercontentMapper;

    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @Resource
    private LetterMapper letterMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public List<ChatRoom> getChatRoomList(Long u_id) {
        List<ChatRoom> list = chatDao.getChatRoomList(u_id);
        for (ChatRoom room : list) {
            Letter letter = letterMapper.selectByPrimaryKey(room.getId());
            room.setUserId(Objects.equals(letter.getUserId(), u_id) ? letter.getUser2Id() : letter.getUserId());
            User user = userMapper.selectByPrimaryKey(room.getUserId());
            room.setUserName(user.getName());
            room.setUserAvatar(Constants.AVATAR_URL + user.getAvatar());
        }
        return list;
    }

    @Override
    public Long getChatRoom(Long one, Long another) {
        Long chatRoom = chatDao.getChatRoom(one, another);
        if (chatRoom == null) {
            chatDao.newChatRoom(one, another);
            chatRoom = chatDao.getChatRoom(one, another);
        }
        return chatRoom;
    }

    @Override
    public List<Lettercontent> getChatHistory(Long one, Long another) {
        Long chatRoom = chatDao.getChatRoom(one, another);
        return chatRoom == null ? new ArrayList<>() : chatDao.getChatHistory(chatRoom);
    }

    @Override
    public void submit(Lettercontent lettercontent, Long user) {
        if (lettercontent.getLetterId() == null) {
            Long chatRoom = chatDao.getChatRoom(user, lettercontent.getUserId());
            lettercontent.setLetterId(chatRoom == null ?
                    chatDao.newChatRoom(user, lettercontent.getUserId()): chatRoom);
        }
        Long receive = lettercontent.getUserId();
        lettercontent.setUserId(user);
        lettercontentMapper.insert(lettercontent);
        applicationEventPublisher.publishEvent(new LetterEvent(this, receive, lettercontent.getLetterId()));
    }
}
